<?php
/**
 * Created by PhpStorm.
 * User: front
 * Date: 2018/8/3
 * Time: 16:39
 */

namespace App\Services;

use App\Exceptions\ApiException;
use App\Jobs\SnsQueue;
use App\Models\MessagesSentSucceed;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class SnsService
{

    /*
     * @mobile string or array   手机组
     * @msg_id int  消息id：默认0
     * @type   int  发送类型
     * @distinct boolen 是否去重复发送
     * */
    public static function send_message_queue($mebile, $msg_id =0, $type = 0, $distinct = false)
    {
        if(empty($mebile))
            return false;

        $mebile_arr = [];
        if(!is_array($mebile))
            $mebile_arr = explode(',', $mebile);
        else
            $mebile_arr = $mebile;

        $sns_key = 'sns:'.$msg_id.':'.$type;
        foreach ($mebile_arr as $key => $m) {
            $m = str_replace('+86', '', $m);
            if (!preg_match('/^(\+86(\-)?)?1[345789]\d{9}$/', str_replace(' ', '', $m))) {
                unset($mebile_arr[$key]);
                continue;
            }

            // 检验是否已发送过
            if($distinct == true){
                $temp_mss = MessagesSentSucceed::where(['msg_id'=>$msg_id, 'msg_type' =>$type, 'mobile' =>$m])->first();
                if(!empty($temp_mss)){
                    unset($mebile_arr[$key]);
                    continue;
                }
            }
            // type 0:推广短信;1:通讯录邀请;
            Redis::zadd($sns_key, [$m =>$m]);
        }

        // 发送短信
        $count = Redis::zcard($sns_key);
        // 创建队列 type:accumulation_send 累加发送
        if($count >= config('basic.xs_sns.xs_sns_batch_num')){

            // 短信通道配置签名
            $xs_sns_sign = config('basic.xs_sns.xs_sns_sign');
            $content = trans('notice.10238');
            // 检验短信内容
            if(stripos($content, $xs_sns_sign) === false){
                add_error_log('address_book_send', ['message'=>'获取发送内容异常']);
                return false;
            }

            $data = ['action'=>'accumulation_send', 'data'=>['msg_id'=>$msg_id, 'msg_type'=>$type, 'content'=>$content]];
            dispatch((new SnsQueue($data))->onQueue('sns_queue'));
        }
        return true;
    }

}